<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="680px"
      :show-close="false"
      :before-close="resetDialog">
      <div slot="title"
           style="display:flex;justify-content:space-between;">
        <div style="display:flex;justify-content:flex-start;font-weight:600;color:#404040;">
          <span class="cursor_pointer cuifont icon_arrow_left"
                @click="dialogVisible = false"
                style="margin-right:10px;padding:7px;font-size:14px;margin-top:-7px"></span>
          <span style="font-size: 16px;color: #404040;">{{title}}</span>
        </div>
        <div style="color:#404040;font-weight:400">
          <span style="font-size:14px;padding:7px;margin-left:10px"
                class="cursor_pointer cuifont icon_dismiss"
                @click="dialogVisible=!dialogVisible"></span>
        </div>
      </div>
      <div style="height:100%">
        <div style="height:32px;margin-bottom:18px;display:flex;justify-content:space-between;align-items:center">
          <el-dropdown placement="bottom-start">
            <span class="el-dropdown-link dropdown_value cursor_pointer">
              {{dropdownValue}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" style="width:200px">
              <el-dropdown-item v-for="item in ['All Tenants','Custom Tenants']" :key="item">
                <div @click="dropdownValue=item,clickHandler(item)" :class="dropdownValue===item?'active_dropdown': ''" style="display:flex;justify-content:space-between;align-items:center">
                  <span>{{item}}</span>
                  <span v-if="dropdownValue===item" class="el-icon-check"></span>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-input placeholder="Search"
                    style="width:200px;"
                    prefix-icon="el-icon-search"
                    clearable
                    @input="keyWordsChange"
                    v-model="keyWords">
          </el-input>
        </div>
        <div v-if="dropdownValue==='All Tenants'">
          <el-table height="587" key="All Tenants" v-loading="loading"
          ref="table"
            :data="tenantList.filter(data => !keyWordsValue || data.tenantName.toLowerCase().includes(keyWordsValue.toLowerCase()))"
            @selection-change="handleSelectionChange"
            style="width: 100%;border:1px solid #DCDFE6">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="tenantName"
              label="Tenant">
            </el-table-column>
          </el-table>
        </div>
        <div v-else-if="dropdownValue==='Custom Tenants'">
          <el-table  key="Custom Tenants" height="587" v-loading="loading"
          ref="table"
            :data="tenantList.filter(data => !keyWordsValue || data.name.toLowerCase().includes(keyWordsValue.toLowerCase()))"
            style="width: 100%;border:1px solid #DCDFE6">
            <el-table-column prop="id" width="50">
              <template slot-scope="scope">
                <el-radio v-model="layerId" :label="scope.row.id"></el-radio>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="Tenant">
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okHander(title)" size="mini">{{title.split(' ')[1]}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { debounce } from 'lodash'
export default {
  data () {
    return {
      dialogVisible: false,
      loading: false,
      title: '',
      appInfo: {},
      list: [
        { id: 1, name: 'Default Install', description: 'Install the current app as a built-in app, applicable to all tenants.' },
        { id: 2, name: 'Mandatory Install', description: 'Select tenants to forced-install the current app.' },
        { id: 3, name: 'Mandatory Uninstall', description: 'Select tenants to forced-uninstall the current app.' },
        { id: 4, name: 'Mandatory Update', description: 'Select tenants to forced-update the current app.' }
      ],
      defaultInstall: false,
      tenantList: [],
      multipleSelection: [],
      item: '',
      id: '',
      keyWords: '',
      keyWordsValue: '',
      dropdownValue: 'All Tenants',
      layerId: ''
    }
  },
  watch: {
    dialogVisible (val) {
      if (!val) {
        this.resetDialog()
      }
    }
  },
  methods: {
    keyWordsChange: debounce(function (val) {
      this.keyWordsValue = val
    }, 1000),
    clickHandler (val) {
      this.tenantList = []
      this.layerId = ''
      if (val === 'All Tenants') {
        this.init(this.id, this.item)
      } else if (val === 'Custom Tenants') {
        this.getLayerList()
      }
    },
    getLayerList () {
      this.layerId = ''
      this.loading = true
      var params = {
        datasetKey: '0006b51c-d7d2-4f1f-83ac-3a1b71c6ae06'
      }
      this.$interface.reports.getDatasetLayerList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.tenantList = res.data
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    okHander (text) {
      if (this.dropdownValue === 'All Tenants') {
        var arr = []
        this.$refs.table.selection.forEach(item => {
          arr.push(item.tenantCode)
        })
        if (arr.length === 0) return this.$message.error('Please Select')
        switch (text) {
          case 'Mandatory Install':
            this.installAll(arr)
            break
          case 'Mandatory Uninstall':
            this.uninstallAll(arr)
            break
          case 'Mandatory Update':
            this.updateAll(arr)
            break
          default:
            break
        }
      } else if (this.dropdownValue === 'Custom Tenants') {
        if (!this.layerId) return this.$message.error('Please Select')
        switch (text) {
          case 'Mandatory Install':
            this.installAll([], this.layerId)
            break
          case 'Mandatory Uninstall':
            this.uninstallAll([], this.layerId)
            break
          case 'Mandatory Update':
            this.updateAll([], this.layerId)
            break
          default:
            break
        }
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    defaultInstallConfirm (defaultInstall) {
      var params = {
        defaultInstall: defaultInstall,
        id: this.appInfo.id
      }
      this.loading = true
      this.$interface.reports.postDefaultInstallApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          this.$message.success('Success')
          this.loading = false
        }).catch(() => { this.loading = false })
    },
    resetDialog () {
      Object.assign(this.$data, this.$options.data())
    },
    init (id, item) {
      this.item = item
      this.id = id
      this.title = item.name
      var params = {
        id: id
      }
      this.loading = true
      this.$interface.reports.getAppInfoApi(params)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.appInfo = res.data
          if (!res.data.installedTenant) res.data.installedTenant = []
          if (!res.data.notInstalledTenant) res.data.notInstalledTenant = []
          this.$nextTick(() => {
            if (this.title === 'Mandatory Install') {
              this.tenantList = res.data.notInstalledTenant
            } else if (this.title === 'Mandatory Uninstall') {
              this.tenantList = res.data.installedTenant
            } else if (this.title === 'Mandatory Update') {
              this.tenantList = res.data.installedTenant
            }
          })
        }).catch(() => { })
    },
    installAll (selectedInstallTenant, layerId) {
      this.$confirm(this.$t('custom.apps.deleteconfirm'), this.$t('custom.apps.warning'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        // type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        var params = {
          'appId': this.appInfo.appId,
          'tenantList': selectedInstallTenant,
          'all': false,
          layerId
        }
        this.loading = true
        this.$interface.reports.postAddToMyAppsApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.loading = false
              return this.$message.error(res.msg)
            }
            this.$message.success('Success')
            if (this.dropdownValue === 'All Tenants') {
              this.init(this.id, this.item)
            } else {
              this.getLayerList()
            }
            // this.loading = false
          }).catch(() => { this.loading = false })
      })
    },
    uninstallAll (selectedUninstallTenant, layerId) {
      this.$confirm(this.$t('custom.apps.deleteconfirm'), this.$t('custom.apps.warning'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        // type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        var params = {
          'appId': this.appInfo.appId,
          'tenantList': selectedUninstallTenant,
          'all': false,
          layerId
        }
        this.loading = true
        this.$interface.reports.deleteMyAppsApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          if (this.dropdownValue === 'All Tenants') {
            this.init(this.id, this.item)
          } else {
            this.getLayerList()
          }
          this.$message.success('Success')
          // this.loading = false
        }).catch(() => { this.loading = false })
      })
    },
    updateAll (selectedUpdateTenant, layerId) {
      this.$confirm(this.$t('custom.apps.deleteconfirm'), this.$t('custom.apps.warning'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        // type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        var params = {
          'appId': this.appInfo.appId,
          'tenantList': selectedUpdateTenant,
          'all': false,
          layerId
        }
        this.loading = true
        this.$interface.reports.postUpdateAllApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.loading = false
              return this.$message.error(res.msg)
            }
            this.$message.success('Success')
            if (this.dropdownValue === 'All Tenants') {
              this.init(this.id, this.item)
            } else {
              this.getLayerList()
            }
            // this.loading = false
          }).catch(() => { this.loading = false })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.cursor_pointer {
  cursor: pointer;
}
.cursor_pointer:hover {
  cursor: pointer;
  color: $--theme-color;
  background-color: $--theme-color-background;
  border-radius: 4px;
}
.more {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 .text_more {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp:3;
  overflow: hidden;
  text-overflow: ellipsis;
}
.active_dropdown {
  color: $--theme-color;
}
.bgc_hover:hover {
  background-color: $--theme-color-background;
  color: $--theme-color;
}
.color_hover:hover {
  color: $--theme-color!important;
}
::v-deep .el-dialog__header {
  height: 54px;
  box-shadow: 0px 1px 0px 0px rgba(240, 240, 240, 0.5);
}
::v-deep .el-dialog__body {
  height: 670px;
}
.dropdown_value {
  background-color: $--theme-color-background;
  color: $--theme-color;
  padding: 8px;
  border-radius: 3px;
}
::v-deep .el-dropdown-menu {
  width: 200px;
}
::v-deep .el-radio__label {
  display: none;
}
</style>
